#!/bin/bash

# 检查密钥文件
KEY_FILE="key.txt"

check_key_file() {
    if [ ! -f "$KEY_FILE" ]; then
        echo "Error: Key file not found: $KEY_FILE" >&2
        exit 1
    fi
    local key_perms=$(stat -c %a "$KEY_FILE")
    if [ "$key_perms" != "600" ]; then
        echo "Warning: Fixing key file permissions to 600"
        chmod 600 "$KEY_FILE"
    fi
}

get_encryption_key() {
    local key=$(cat "$KEY_FILE")
    if [ -z "$key" ]; then
        echo "Error: Empty key file" >&2
        exit 1
    fi
    echo "$key"
}

encrypt_password() {
    local password="$1"
    local key=$(get_encryption_key)
    echo "$password" | openssl enc -aes-256-cbc -a -salt -pass pass:"$key"
}

decrypt_password() {
    local encrypted_password="$1"
    local key=$(get_encryption_key)
    echo "$encrypted_password" | openssl enc -aes-256-cbc -a -d -salt -pass pass:"$key"
}

# (FIXED) 加密acc文件中的密码列，支持5列格式
encrypt_acc_file() {
    local temp_file=$(mktemp)
    # 读取明文的 acc.plain 文件
    if [ ! -f "acc.plain" ]; then
        echo "Error: Plaintext file 'acc.plain' not found for encryption." >&2
        exit 1
    fi

    # (FIXED) 更新 read 以处理5列
    while IFS=' ' read -r ip user password protocol conn_port; do
        if [ -n "$ip" ]; then
            encrypted_pass=$(encrypt_password "$password")
            # (FIXED) 输出所有列，只替换密码列
            echo "$ip $user $encrypted_pass $protocol $conn_port" >> "$temp_file"
        fi
    done < "acc.plain"

    # 用加密后的内容覆盖 acc 文件并设置权限
    mv "$temp_file" "acc"
    chmod 600 "acc"
    # 安全删除明文文件
    shred -u "acc.plain"
}

# (FIXED) 解密acc文件中的密码列，支持5列格式
decrypt_acc_file() {
    while IFS=' ' read -r ip user encrypted_pass protocol conn_port; do
        if [ -n "$ip" ]; then
            decrypted_pass=$(decrypt_password "$encrypted_pass")
            # (FIXED) 输出所有列，并替换为解密后的密码
            echo "$ip $user $decrypted_pass $protocol $conn_port"
        fi
    done < "acc"
}

clean_variables() {
    unset key password encrypted_pass decrypted_pass
}

main() {
    check_key_file

    case "$1" in
        encrypt)
            encrypt_acc_file
            echo "File 'acc.plain' has been encrypted to 'acc' and securely deleted."
            ;;
        decrypt)
            if [ ! -f "acc" ]; then
                # 静默退出，避免cron日志污染
                exit 0
            fi
            decrypt_acc_file
            ;;
        *)
            echo "Usage: $0 {encrypt|decrypt}" >&2
            echo "Note: 'encrypt' reads from 'acc.plain' and writes to 'acc'." >&2
            exit 1
            ;;
    esac
}

trap clean_variables EXIT
main "$@"
